package com.example.androidsensors;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class RowAdapter extends ArrayAdapter<SensorBean>{
	Context context;
	int layoutResourceId;
	SensorBean data[];
	
	public RowAdapter(Context context, int layoutResourceId, SensorBean[] data){
		super(context, layoutResourceId, data);
		this.context = context;
		this.layoutResourceId = layoutResourceId;
		this.data = data;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent){
		View row = convertView;
		SensorBeanHolder holder=null;
		SensorBean object = data[position];
		
		if(row==null){
			LayoutInflater inflater =((Activity)context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);
			
			holder = new SensorBeanHolder();
			holder.name = (TextView) row.findViewById(R.id.sensorName);
			holder.x = (TextView) row.findViewById(R.id.xAxis);
			holder.y = (TextView) row.findViewById(R.id.yAxis);
			holder.z = (TextView) row.findViewById(R.id.zAxis);
			holder.active = (CheckBox) row.findViewById(R.id.activeCheckBox);
			row.setTag(holder);
		}
		else{
			holder = (SensorBeanHolder)row.getTag();
		}
		if(!object.isActive()){
			holder.x.setVisibility(View.GONE);
			holder.y.setVisibility(View.GONE);
			holder.z.setVisibility(View.GONE);
		}else{
			holder.x.setVisibility(View.VISIBLE);
			holder.y.setVisibility(View.VISIBLE);
			holder.z.setVisibility(View.VISIBLE);
		}
		
		holder.name.setText(object.getName());
		if(object.getSensor().getType() == 3){
			holder.x.setText("Azimuth: " + object.getX());
			holder.y.setText("Pitch: " + object.getY());
			holder.z.setText("Roll: " + object.getZ());
		} else if(object.getSensor().getType() == Sensor.TYPE_PROXIMITY){
			holder.x.setText("X: " + object.getX());
			holder.y.setVisibility(View.GONE);
			holder.z.setVisibility(View.GONE);
		} else {
			holder.x.setText("X: " + object.getX());
			holder.y.setText("Y: " + object.getY());
			holder.z.setText("Z: " + object.getZ());
		}
		holder.active.setChecked(object.isActive());
		
		return row;
	}
	
	static class SensorBeanHolder{
		TextView name;
		TextView x;
		TextView y;
		TextView z;
		CheckBox active;
	}
}
